package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.constant.ClueStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDo;
import com.qk.domain.clue.ClueDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CourseMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 *
 * @author MrZhao
 * @created 2025-10-15 10:53
 * @description 商机业务实现类
 *
 */
@Slf4j
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void addBusiness(BusinessDTO dto) {
        log.info("添加商机：{}", dto);
        //参数校验,只校验客户姓名和手机号
        boolean hasNullField = BeanUtil.hasNullField(dto, "name", "phone");
        if (hasNullField) {
            log.error("参数有误");
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }

        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        this.save(business);
    }

    @Override
    public PageResult<BusinessDo> businessList(BusinessListDTO dto) {
        Page pages = new Page(dto.getPage(),dto.getPageSize());
        Page<BusinessDo> businessDoPage = this.baseMapper.selectByPageMp(pages, dto);
        return PageResult.<BusinessDo>builder()
                .total(Long.valueOf(businessDoPage.getTotal()).intValue())
                .rows(businessDoPage.getRecords())
                .build();
    }

    @Override
    public PageResult<Business> getPool(BusinessPoolDTO dto) {
        Page pages = new Page(dto.getPage(),dto.getPageSize());
        Page<Business> businessPage = this.baseMapper.selectByPageP(pages, dto);
        return PageResult.<Business>builder()
                .total(Long.valueOf(businessPage.getTotal()).intValue())
                .rows(businessPage.getRecords())
                .build();
    }

    @Override
    public void updateBusinessInfoById(UpdateBusinessInfoDTO dto) {
        log.info("=========================Service 中 方法updateBusinessInfoById 处理线程名称是：{}",Thread.currentThread().getName());
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        if (dto.getStatus() == BusinessStatusConstants.WAIT_FOLLOW_UP){
            business.setStatus(BusinessStatusConstants.FOLLOW_UP);
        }
        this.updateById(business);
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(business.getId());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        this.businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(
                Wrappers.lambdaQuery(BusinessTrackRecord.class)
                        .eq(BusinessTrackRecord::getBusinessId, id)
        );
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.TrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.TrackRecordVO vo = BeanUtil.copyProperties(item, BusinessVO.TrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        // 设置跟进记录
        businessVO.setTrackRecords(list);
        return businessVO;
    }

    @Override
    public void toCustomer(Integer id) {
        Business business =this.baseMapper.selectById( id);
        business.setStatus(BusinessStatusConstants.TO_CUSTOMERS);
        business.setUpdateTime(LocalDateTime.now());
        business.setSourceType(1); // 标识为商机转化的客户
        this.updateById(business);
    }
}